﻿using System;
using System.Drawing;
using System.Linq;
using Portal.Core.Helper;
using Portal.Core.Utils;
using Portal.Data;
using Portal.Data.Entity;

namespace Ajax.UserControl
{
    public partial class Ajax_UserControl_Content : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var action = Request["act"];
            dynamic jdata = new DynamicJsonObject();
            var user = PortalContext.CurrentUser;
            int bid, cid;
            Content c;
            switch (action)
            {
                case "removeFromChapter":
                    if (user == null)
                        return;

                    int.TryParse(Request["bid"], out bid);
                    int chapterdel, tochapter;
                    int.TryParse(Request["chapter"], out chapterdel);
                    int.TryParse(Request["tochapter"], out tochapter);
                    if (bid > 0 && chapterdel > 0)
                    {
                        var book = Book.FindByPrimaryKey(bid);
                        if (book != null)
                            Content.RemoveFromChapter(book, chapterdel, tochapter);
                    }
                    Response.Write("Xong");
                    Response.End();

                    break;

                case "autoCrawl":    //auto crawl chuong moi
                    int.TryParse(Request["bid"], out bid);
                    if (bid <= 0)
                    {
                        jdata.msg = "<span style='color:red !important;'>Hãy chọn sách trước đã!</span>";
                    }
                    else
                    {
                        var b = Book.FindByPrimaryKey(bid);
                        if (b != null)
                        {
                            if (b.Finish)
                            {
                                jdata.msg = "<span style='color:red !important;'>Truyện đã kết thúc!</span>";
                            }
                            else
                            {
                                string errMessage;
                                jdata.total = Content.AutoCrawler(b, out errMessage);
                                jdata.msg = errMessage;
                            }
                        }
                        else
                        {
                            jdata.msg = "<span style='color:red !important;'>Sách với mã số <b>" + bid +
                                           "</b> không tồn tại!</span>";
                        }
                    }
                    break;
                case "reCrawlData":
                    int.TryParse(Request["cid"], out cid);
                    c = Content.FindByPrimaryKey(cid);
                    if (c != null)
                    {
                        var newdata = Content.ReCrawler(cid);
                        if (newdata.Length > 0)
                        {
                            Content.SetBody(c.Book_ID, c.ID, newdata);
                            c.Broken = false;
                            c.UpdateOnly();
                        }

                        Response.Write(c.Broken ? "Vẫn hỏng!" : "<span style='color:green !important;'>Good!</span>");
                        Response.End();
                    }
                    else
                    {
                        Response.Write("Không thấy content có ID=" + cid);
                        Response.End();
                    }
                    break;
                case "reCrawlFromChap":
                    int.TryParse(Request["cid"], out cid);
                    c = Content.FindByPrimaryKey(cid);
                    if (c != null)
                    {
                        var all = Content.FindByBook(c.Book_ID).Where(o => o.Chapter >= c.Chapter).ToList();
                        var errmsg = "";
                        foreach (var item in all)
                        {
                            var newdata = Content.Crawler(item.CrawlUrl);
                            if (newdata.Length > 0)
                            {
                                Content.SetBody(item.Book_ID, item.ID, newdata);
                                item.Broken = false;
                                item.UpdateOnly();
                            }
                            else
                            {
                                errmsg += item.ID + ",";
                            }
                        }
                        jdata.msg = "<span style='color:green !important;'>Crawl thành công. " + (errmsg.Length > 0 ? "Vẫn còn các id không có dữ liệu: " + errmsg : "") + "</span>";
                    }
                    else
                    {
                        jdata.msg = "Không thấy content có ID=" + cid;
                    }
                    break;

                case "gochap":
                    int.TryParse(Request["bid"], out bid);
                    var chapter = 0;
                    int.TryParse(Request["chap"], out chapter);
                    if (bid > 0 && chapter > 0)
                    {
                        var gochap = Content.FindByChapter(bid, chapter);
                        if (gochap != null)
                            jdata.msg = gochap.URL;
                    }
                    break;
                case "delete":
                    if (user == null)
                        return;
                    int delchapid;
                    int.TryParse(Request["cid"], out delchapid);
                    if (delchapid > 0)
                    {
                        c = Content.FindByPrimaryKey(delchapid);
                        if (c != null)
                            c.Delete();
                    }
                    break;
                case "incrview":
                    //increate viewed
                    int bookId, chapid;
                    int.TryParse(Request["bid"], out bookId);
                    int.TryParse(Request["cid"], out chapid);
                    if (bookId > 0)
                        IncrView(bookId, chapid);
                    break;
                case "cropImage":
                    jdata.err = 1;
                    var imgUploaded = Request["imgul"];
                    var imgModified = Request["imgmd"];

                    var x = Request["x"];
                    var y = Request["y"];
                    var w = Request["w"];
                    var h = Request["h"];
                    if (string.IsNullOrEmpty(imgModified) || string.IsNullOrEmpty(x) || string.IsNullOrEmpty(y)
                        || string.IsNullOrEmpty(w) || string.IsNullOrEmpty(h))
                    {
                        jdata.msg = "Có lỗi do dữ liệu không đầy đủ!";
                    }
                    else
                    {
                        //make crop from origin image upload
                        var isSlideCrop = Request["slide"].Equals("true", StringComparison.OrdinalIgnoreCase);
                        var subfix = (isSlideCrop) ? "slide" : null;
                        var savePath = ImageHelper.Instance.CropImage(imgUploaded,
                                                                         new Rectangle(Convert.ToInt32(x),
                                                                                       Convert.ToInt32(y),
                                                                                       Convert.ToInt32(w),
                                                                                       Convert.ToInt32(h)), subfix);
                        jdata.msg = savePath;
                        jdata.err = 0;
                    }
                    break;
            }

            Response.Write(jdata.ToString());
            Response.End();
        }
        void IncrView(int bookId, int chapid)
        {
            var key = "Book@" + Session.SessionID + bookId + chapid;
            if (Session[key] == null)
            {
                Session[key] = 1;
                //make reading by day, and using for visited by day
                Portal.Data.Queue.IncreaseBookView.IncrView(bookId);
            }
        }
    }
}